﻿/**
 * Multipart Data Form Helper
 * 
 * Simple class to send binary and text data in one request
 * like HTML <form method="multipart/form-data" ... > do
 * 
 * Released under MIT license:
 * http://www.opensource.org/licenses/mit-license.php 
 * 
 * How to use:
 * 
 * var loader:URLLoader = new URLLoader();
 * var multipartForm:MultipartForm = new MultipartForm("http://example.com/upload.php");
 * multipartForm.getRequest().method = URLRequestMethod.POST;
 * multipartForm.addField("name_text_field", "Name of example picture"); // Add simple field with text
 * multipartForm.addFile("picture_file", "picture.jpg", "image/jpeg", jpg_binary); // Add field with JPG file data
 * loader.load(multipartForm.getRequest());
 * 
 **/

package com.dawidgorny.net 
{
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.net.URLRequestHeader;
	
	/**
	 * MultipartForm
	 * @author Dawid Górny <hello@dawidgorny.com>
	 */
	public class MultipartForm
	{
		
		protected static const BOUNDARY:String = "---------------------------7d76d1b56035e";
		protected var encoding:String = "utf-8";
		protected var acceptHeader:URLRequestHeader;
		
		protected var formData:ByteArray;
		
		protected var request:URLRequest;
		
		public function MultipartForm(url:String = null) 
		{
			this.request = new URLRequest(url);
			resetRequest();
		}
		
		public function resetRequest()
		{
			this.request.contentType = "multipart/form-data; boundary=" + MultipartForm.BOUNDARY;
			this.acceptHeader = new URLRequestHeader("Accept", "text/*");
			this.request.requestHeaders.push(this.acceptHeader);
			this.formData = new ByteArray();
		}
		
		public function addField(fieldName:String, value:*) 
		{
			this.formData.writeMultiByte("--" + MultipartForm.BOUNDARY + '\r\nContent-Disposition: form-data; name="' + fieldName + '"\r\n\r\n' + value + '\r\n' , this.encoding);
		}
		
		public function addFile(fieldName:String, fileName:String, contentType:String, content:*) 
		{
			this.formData.writeMultiByte("--" + MultipartForm.BOUNDARY + '\r\nContent-Disposition: form-data; name="' + fieldName + '"; filename="' + fileName + '"\r\nContent-Type: ' + contentType + '\r\n\r\n', this.encoding);
			this.formData.writeBytes(content);
			this.formData.writeMultiByte('\r\n' , "utf-8");
			this.formData.writeMultiByte( "--" + MultipartForm.BOUNDARY + '--', this.encoding);
		}
		
		public function getRequest():URLRequest
		{
			this.request.data = this.formData;
			return this.request;
		}
		
	}
	
}